/*
* ajax请求模块
* */
//基于axios  promise的HTTP库

import axios from 'axios'

export default function ajax (url = '', data = {}, type = 'GET') {
// 高级函数 直接调用data
// 请求成功 调用resolve.data  失败返回error
//   console.log(data)
  return new Promise(function (resolve, reject) {
    // console.log(type)
    let promise
    if (type == 'GET') {
      let dataStr = ''
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + dataStr[key] + '&'
      })
      if (dataStr != '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      // get请求
      promise = axios.get(url)
    } else {
      // post请求
      promise = axios.post(url, data)
    }
    promise.then(response => {
      resolve(response.data)
    }).catch(error => {
      reject(error)
    })
  })
}

